package com.liaoyin.travel.service.scenicInfo;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.view.scenic.ScenicInfoView;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.scenicInfo.*;
import com.liaoyin.travel.entity.BackUser;
import com.liaoyin.travel.entity.scenicInfo.AreaCity;
import com.liaoyin.travel.entity.scenicInfo.ScenicAdmin;
import com.liaoyin.travel.entity.scenicInfo.ScenicInfo;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.approval.VisualRangeSettingService;
import com.liaoyin.travel.service.back.BackUserService;
import com.liaoyin.travel.util.*;
import com.liaoyin.travel.vo.scenic.AuditScenicVo;
import com.liaoyin.travel.vo.scenic.InsertOrUpdateScenicVo;
import com.liaoyin.travel.vo.scenic.SelectScenicVo;
import org.apache.commons.lang3.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 景区管理 service
 *
 * @author Kuang.JiaZhuo
 * @date 2020-02-21 11:18
 */
@Service
public class ScenicInfoService extends BaseService<ScenicInfoMapper, ScenicInfo> {

    @Resource
    BackUserService backUserService;
    @Resource
    ScenicAdminService scenicAdminService;
    @Resource
    UsersService usersService;
    @Resource
    AreaService areaService;
    @Resource
    VisualRangeSettingService visualRangeSettingService;
    @Resource
    ScenicInfoMapper scenicInfoMapper;
    @Resource
    ScenicAdminMapper scenicAdminMapper;

    /**
     * @方法名：insertOrUpdateScenicInfo
     * @描述： 新增或更新 景区信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/21 13:13
     */
    @Transactional(rollbackFor = BusinessException.class)
    public int insertOrUpdateScenicInfo(InsertOrUpdateScenicVo insertOrUpdateScenicVo) throws ParseException {
        //最终返回结果
        int result = 0;
        //景区id
        String scenicId = insertOrUpdateScenicVo.getScenicId();
        //身份证号
        String identityCard = insertOrUpdateScenicVo.getIdentityCard();
        //电话号码
        String phone = insertOrUpdateScenicVo.getPhone();
        //性别
        String gender = insertOrUpdateScenicVo.getGender();
        //账号
        String account = insertOrUpdateScenicVo.getAccount();
        //管理员密码
        String password = insertOrUpdateScenicVo.getPassword();
        //当日最大承载量
        BigInteger maximumCapacityForTheDay = insertOrUpdateScenicVo.getMaximumCapacityForTheDay();
        //单位类型
        String unitType = insertOrUpdateScenicVo.getUnitType();
        //机构类型
        String organType = insertOrUpdateScenicVo.getOrganType();
        //设备编号
        String equipmentNumbers = insertOrUpdateScenicVo.getEquipmentNumber();
        //文旅资源状态【1.应急】
        Integer emergency = insertOrUpdateScenicVo.getEmergency();
        //应急文旅资源ID
        String emergencyId = insertOrUpdateScenicVo.getEmergencyId();
        //应急文旅资源ID
        String resourceType = insertOrUpdateScenicVo.getResourceType();

        //验证身份证号的数据有效性
        /*if(!ValidateUtil.validateIDCard(identityCard)){
            throw new BusinessException("wrong.id.number");
        }*/

        if (phone != null && !phone.equals("")) {
            //验证电话号码的数据有效性
            if (PhoneUtil.isPhone(phone) == null) {
                throw new BusinessException("phone.is.mistake");
            }
        }
        //验证文旅资源名称是否重复
        judgeUnauditedScenicNameIsReDo(insertOrUpdateScenicVo.getScenicName(),scenicId,resourceType);

        //验证性别的数据有效性
        /*if(!VariableConstants.STRING_CONSTANT_1.equals(gender) && !VariableConstants.STRING_CONSTANT_2.equals(gender)){
            throw new BusinessException("gender.is.fault");
        }*/


        ScenicAdmin scenicAdmin = new ScenicAdmin()
                //身份证号
//                .setIdentityCard(identityCard)
                //电话号码
                .setPhone(phone.equals("") ? null : phone)
                //性别
//                .setGender(gender)
                //景区管理员姓名
                .setName(insertOrUpdateScenicVo.getAdminName())
                //账号
                .setAccount(account)
                //密码
                .setPassword(MD5Util.Base64Encode(password));

        ScenicInfo scenicInfo = new ScenicInfo()
                //区域(暂定精确到区)id
                .setDistrictId(insertOrUpdateScenicVo.getDistrictId())
                //景区名字
                .setScenicName(insertOrUpdateScenicVo.getScenicName())
                //公司名字
                .setCorpName(insertOrUpdateScenicVo.getCorpName())
                //当天最大承载量
                .setMaximumCapacityForTheDay(maximumCapacityForTheDay)
                //单位类型
                .setUnitType(unitType)
                //机构类型
                .setOrganType(organType);


        //设备编号
        if (!StringUtil.isBlank(equipmentNumbers)) {
            List<String> numbers = Arrays.asList(equipmentNumbers.split(","));
            judgeEquipmentNumberRepetition(numbers, scenicId);
            HashSet<String> equipmentNumberSet = new HashSet<>(numbers);
            StringBuilder equipmentNumberSB = new StringBuilder();
            int i = 0;
            for (String number : equipmentNumberSet) {
                equipmentNumberSB.append(number);
                if (i < equipmentNumberSet.size() - 1) {
                    equipmentNumberSB.append(",");
                    i++;
                }
            }
            String equipmentNumberStr = equipmentNumberSB.toString();
            scenicInfo.setEquipmentNumber(equipmentNumberStr);
        }

        //应急文旅资源状态
        if (emergency != null && emergency == 1) {
            scenicInfo.setEmergency(emergency);
            scenicInfo.setEmergencyId(emergencyId);
            //如果资源为应急文旅资源，那么应急资源ID必须存在
            if (StringUtils.isBlank(emergencyId)){
                throw new BusinessException("Emergency.Resource.Format.Error");
            }
            //通过应急文旅资源ID判断应急文旅资源是否已经存在
            judgeEmergencyIdIsReDo(emergencyId, scenicId);

        }

        if (StringUtil.isBlank(scenicId)) {


            //新增时单位类型不能为空
            Optional.ofNullable(unitType).orElseThrow(() -> new BusinessException("unitType.is.null"));
            //验证单位类型数据有效性
            ServiceUtil.verifyUnitTypeValidity(unitType);

            if (VariableConstants.STRING_CONSTANT_1.equals(unitType)) {
                //新增景区时 当日最大承载量不能为空
                if (maximumCapacityForTheDay == null) {
                    throw new BusinessException("maximumCapacityForTheDay.is.null");
                }
            } else if (VariableConstants.STRING_CONSTANT_2.equals(unitType)) {
                //新增机构时,机构类型不能为空
                if (organType == null || organType.equals("")) {
                    throw new BusinessException("organType.is.null");
                }
            }


            /** 新增 */
            scenicId = SnowIdUtil.getInstance().nextId();

            //判断身份证号是否重复
//            judgeIdentityCardIsReDo(identityCard,null);

            //判断账号或电话是否重复，若重复会抛出异常
            judgeAccountIsReDo(account, phone,scenicId);
            //判断未审核的账号是否存在重复
            judgeUnauditedAccountIsReDo(account, phone);

            scenicInfo.setId(scenicId).setCreateTime(LocalDateTime.now())
                    .setIsPassed(VariableConstants.STRING_CONSTANT_0)
                    //审核状态
                    .setAuditStatus(VariableConstants.STRING_CONSTANT_0);

            result = this.mapper.insert(scenicInfo);


            scenicAdmin.setScenicId(scenicId)
                    .setCreateTime(LocalDateTime.now())
                    .setId(SnowIdUtil.getInstance().nextId());
            this.scenicAdminService.insert(scenicAdmin);
        } else {

            /** 更新 */
            scenicInfo.setId(scenicId);
            //判断身份证号是否重复
//            judgeIdentityCardIsReDo(identityCard,scenicId);

            //管理员id
            String backUserId = insertOrUpdateScenicVo.getBackUserId();
            System.err.println("backUserId=" + backUserId);
            if (backUserId == null) {
                /** 未过审核，管理员id为空 */
                //判断账号或电话是否重复，若重复会抛出异常
                judgeAccountIsReDo(account, phone,scenicId);
                //判断待审核的景区管理员是否已经存在重复的账号和电话号码，存在会抛出异常
                judgeUnreviewedAccountIsReDo(account, phone, scenicId);

            } else {
                /** 曾过审核，管理员id不为空 */
                List<BackUser> backUsers = this.backUserService.selectBackUserByAccount(account);
                if (backUsers.size() > 0) {
                    backUsers.forEach(backUser -> {
                        //账号相同，id不同 ==》重复
                        if (account.equals(backUser.getAccount()) && !backUser.getId().equals(backUserId)) {
                            System.err.println("backUser.getId()=" + backUser.getId());
                            throw new BusinessException("account.is.exist");
                        }
                    });
                }
                //判断未审核的账号是否存在重复
                judgeUnauditedAccountIsReDo(account, phone);

            }

            scenicInfo.setUpdateTime(LocalDateTime.now());
            System.err.println("scenicInfo=" + scenicInfo);
            result = this.mapper.updateScenicInfoSelective(scenicInfo);

            scenicAdmin.setScenicId(scenicId);
            int count = this.scenicAdminService.updateScenicAdminByScenicId(scenicAdmin);

            if (result == 0) {
                result = count;
            }
        }
        return result;
    }

    /**
     * 通过应急文旅资源ID判断应急文旅资源是否重复
     */
    private void judgeEmergencyIdIsReDo(String emergencyId, String id) {
        //后台用户已经存在相同应急文旅资源
        if (selectBackUserByEmergencyId(emergencyId, id) > 0) {
            throw new BusinessException("Emergency.Resource.Is.Exist");
        }
    }
    /**
     * 通过文旅资源名称判断是否重复
     */
    private void judgeUnauditedScenicNameIsReDo(String scenicName, String id, String resourceType) {
        //后台用户已经存在相同应急文旅资源
        if (countScenicInfoByEmergencyId(scenicName, id) > 0) {
            throw new BusinessException("Resource.Is.Exist",(StringUtils.isNotBlank(resourceType)?resourceType:"文旅资源")+ "名称已存在！");
        }
    }

    /**
     * 判断设备编号是否重复
     *
     * @param numbers
     * @param id
     */
    private void judgeEquipmentNumberRepetition(List<String> numbers, String id) {
        //判断是否和自己存在设备重复
        HashSet<String> numberSet = new HashSet<>(numbers);
        if (numbers.size() != numberSet.size()){
            throw new BusinessException("EquipmentNumber.Repetition", "设备编号重复！");
        }
        //判断是否和其他景区设备重复
        List<ScenicInfo> scenicInfos = scenicInfoMapper.selectAll();
        for (String number : numbers) {
            for (ScenicInfo sif : scenicInfos) {
                String equipmentNumber = sif.getEquipmentNumber();
                if (StringUtils.isNotBlank(equipmentNumber)) {

                    for (String equipmentNumberSplit : sif.getEquipmentNumber().split(",")) {

                        if (equipmentNumberSplit.trim().equals(number.trim())) {
                            if (StringUtils.isNotBlank(id)) {
                                if (!id.equals(sif.getId())) {
                                    throw new BusinessException("EquipmentNumber.Repetition", "设备编号【" + number + "】已存在于文旅资源【" + sif.getScenicName() + "】中！");
                                }
                            } else {
                                throw new BusinessException("EquipmentNumber.Repetition", "设备编号【" + number + "】已存在于文旅资源【" + sif.getScenicName() + "】中！");
                            }
                        }


                    }
                }

            }
        }
    }

    /**
     * @方法名：judgeAccountIsReDo
     * @描述： 判断账号和用户是否重复，若重复会抛出异常
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/21 18:20
     */
    public void judgeAccountIsReDo(String account, String phone, String scenicId) {

        //后台用户已经存在相同账号
        List<BackUser> backUsers = this.backUserService.selectBackUserByAccount(account);
        if (backUsers.size() > 0 || scenicAdminMapper.countScenicAdminByCount(account,scenicId) > 0) {
            throw new BusinessException("account.is.exist");
        }

        /*if(phone!=null && !phone.equals("")){
            //后台用户已经存在相同电话号码
            List<BackUser> backUserList = this.backUserService.selectBackUserByPhone(phone);
            if(backUserList.size()>0){
                throw new BusinessException("phone.is.exist");
            }
        }*/


        /**
         * 判断移动端用户表是否存在相同电话
         * 因为超级管理员要在移动端进行操作，所以建立后台管理员的同时，
         * 也需要在移动端建立一个账号相同的管理员
         */
        /*List<Users> usersList = this.usersService.selectUserListByPhone(phone);
        if(usersList.size()>0){
            throw new BusinessException("phone.is.exist");
        }*/
    }

    /**
     * @方法名：judgeUnreviewedAccountIsReDo
     * @描述： 判断未审核的管理员，除了自身的信息外，账户和电话是存在重复
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/21 21:25
     */
    public void judgeUnreviewedAccountIsReDo(String account, String phone, String scenicId) {
        //待审核的景区管理员已经存在相同账户
        List<ScenicAdmin> scenicAdminList = this.scenicAdminService.selectScenicAdminByAccount(account);
        if (scenicAdminList.size() > 0) {
            scenicAdminList.forEach(scenicAdmin1 -> {
                if (!scenicAdmin1.getScenicId().equals(scenicId)) {
                    throw new BusinessException("account.toAudit.is.exist");
                }
            });
        }
        //待审核的景区管理员已经存在相同电话
        /*List<ScenicAdmin> scenicAdmins = this.scenicAdminService.selectScenicAdminByPhone(phone);
        if(scenicAdmins.size()>0){
            scenicAdmins.forEach(scenicAdmin1 -> {
                if(!scenicAdmin1.getScenicId().equals(scenicId)){
                    throw new BusinessException("phone.toAudit.is.exist");
                }
            });
        }*/
    }

    /**
     * @方法名：judgeIdentityCardIsReDo
     * @描述： 根据身份证号判断账号是否重复, 若重复则抛出异常
     * @作者： kjz
     * @日期： Created in 2020/2/24 17:25
     */
    public void judgeIdentityCardIsReDo(String identityCard, String scenicId) {
        List<ScenicAdmin> scenicAdmins = this.scenicAdminService.selectScenicAdminByIdentityCard(identityCard, scenicId);
        if (scenicAdmins.size() > 0) {
            scenicAdmins.forEach(scenicAdmin1 -> {
                ScenicInfo scenicInfo1 = this.mapper.selectScenicInfoById(scenicAdmin1.getScenicId());
                String auditStatus = scenicInfo1.getAuditStatus();
                if (auditStatus.equals(VariableConstants.STRING_CONSTANT_0)) {
                    throw new BusinessException("scenicAdmin.identityCard.is.exist");
                } else if (auditStatus.equals(VariableConstants.STRING_CONSTANT_2)) {
                    throw new BusinessException("refuse.is.exist");
                }
            });
        }
        List<BackUser> backUsers = this.backUserService.selectBackUserByIdentityCard(identityCard, scenicId);
        if (backUsers.size() > 0) {
            throw new BusinessException("backUser.identityCard.is.exist");
        }
    }

    /**
     * @方法名：judgeUnauditedAccountIsReDo
     * @描述： 判断未审核的管理员，账户和电话是存在重复
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/21 21:40
     */
    public void judgeUnauditedAccountIsReDo(String account, String phone) {
        //待审核的景区管理员已经存在相同账户
        List<ScenicAdmin> scenicAdminList = this.scenicAdminService.selectScenicAdminByAccount(account);
        if (scenicAdminList.size() > 0) {
            throw new BusinessException("account.toAudit.is.exist");
        }
        //待审核的景区管理员已经存在相同电话
        /*if(phone!=null && !phone.equals("")){
            List<ScenicAdmin> scenicAdmins = this.scenicAdminService.selectScenicAdminByPhone(phone);
            if(scenicAdmins.size()>0){
                throw new BusinessException("phone.toAudit.is.exist");
            }
        }*/

    }

    /**
     * @方法名：selectScenicInfoViewByCondition
     * @描述： 按条件查询景区管理的信息(带分页)
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/21 22:57
     */
    public PageInfo<ScenicInfoView> selectScenicInfoViewByCondition(SelectScenicVo selectScenicVo) {
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if (user == null) {
            throw new BusinessException("not.login");
        }
        System.err.println(user.getScenicId());

        PageHelper.startPage(selectScenicVo.getNum(), selectScenicVo.getSize());
        String auditStatus = selectScenicVo.getAuditStatus();
        Optional.ofNullable(auditStatus).orElseThrow(() -> new BusinessException("auditStatus.is.null"));
        List<ScenicInfoView> list = new ArrayList<>();
        //已经通过审核的
        if (VariableConstants.STRING_CONSTANT_1.equals(auditStatus)) {
            list = this.mapper.selectScenicInfoByTermAndOne(selectScenicVo);
        }
        //未审核过的或者拒绝通过的
        if (VariableConstants.STRING_CONSTANT_2.equals(auditStatus) || VariableConstants.STRING_CONSTANT_0.equals(auditStatus)) {
            list = this.mapper.selectScenicInfoByTermAndzeroOrTwo(selectScenicVo);
        }
        list.forEach(scenicInfoView -> {
            String districtId = scenicInfoView.getDistrictId();
            AreaCity areaCity = this.areaService.selectAreaCityByDistrictId(districtId);
            scenicInfoView.setCityId(areaCity.getId()).setProvinceId(areaCity.getProvinceId());
        });
        PageInfo<ScenicInfoView> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * @方法名：selectScenicInfoViewByIdAndAuditStatus
     * @描述： 根据id和审核状态查询景区详情
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/22 0:42
     */
    public ScenicInfoView selectScenicInfoViewByIdAndAuditStatus(String scenicId, String auditStatus) {
        ScenicInfoView scenicInfoView = new ScenicInfoView();
        if (auditStatus.equals(VariableConstants.STRING_CONSTANT_1)) {
            scenicInfoView = this.mapper.selectScenicInfoViewByIdAndStatusOne(scenicId);
        } else {
            scenicInfoView = this.mapper.selectScenicInfoViewByIdAndStatusZeroOrTwo(scenicId);
        }
        if (scenicInfoView != null) {
            String districtId = scenicInfoView.getDistrictId();
            AreaCity areaCity = this.areaService.selectAreaCityByDistrictId(districtId);
            scenicInfoView.setCityId(areaCity.getId()).setProvinceId(areaCity.getProvinceId());
        }
        return scenicInfoView;
    }

    /**
     * @方法名：auditScenic
     * @描述： 文旅委管理员 通过或拒绝景区的申请
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/22 10:42
     */
    @Transactional(rollbackFor = BusinessException.class)
    public int auditScenic(AuditScenicVo auditScenicVo) {
        int result = 0;
        String scenicId = auditScenicVo.getScenicId();
        if (auditScenicVo.getAuditStatus().equals(VariableConstants.STRING_CONSTANT_1)) {
            /** 通过审核 */

            String unitType = auditScenicVo.getUnitType();
            String organType = auditScenicVo.getOrganType();

            String password = auditScenicVo.getPassword();
            String backUserId = null;
            BackUser backUser = new BackUser()
                    .setAccount(auditScenicVo.getAccount())
                    .setUserType(VariableConstants.STRING_CONSTANT_2)
                    .setNickName(auditScenicVo.getAdminName())
//                    .setIdentityCard(auditScenicVo.getIdentityCard())
                    .setPhone(auditScenicVo.getPhone())
//                    .setGender(auditScenicVo.getGender())
                    .setScenicId(scenicId);
            //是否为文旅委管理账号(更改需求后这个逻辑没什么用)
//                    .setIsCommittee(VariableConstants.STRING_CONSTANT_0);

            /*Users users = new Users()
                    //昵称
                    .setNickName(auditScenicVo.getAdminName())
                    //默认启用
                    .setIsUsing(Short.valueOf("1"))
                    //性别
                    .setSex(Short.valueOf(auditScenicVo.getGender()))
                    //身份证号
                    .setIdentityCard(auditScenicVo.getIdentityCard())
                    //景区id
                    .setScenicId(scenicId)
                    //账号
                    .setAccount(auditScenicVo.getPhone())
                    //手机号
                    .setPhone(auditScenicVo.getPhone())
                    //员工类型
                    .setEmptype(unitType);*/

            //查询景区是否是已经通过审核的，若通过审核就不删除，直接更改
            boolean isPass = this.testScenicIsPass(scenicId);
            if (isPass) {
                //更新后台用户
                backUserId = this.selectBackUserIdByScenicId(scenicId);
                backUser.setId(backUserId).setCipher(MD5Util.Base64Encode(password))
                        .setPassword(MD5Util.createPassword(MD5Util.getMD5String(password), backUserId));
                this.backUserService.updateSelectiveById(backUser);

              /* users.setId(backUserId).setPassword(MD5Util.createPassword(MD5Util.getMD5String(password),backUserId));
               this.usersService.updateSelectiveById(users);*/

            } else {
                //删除景区管理员表
                String[] ids = new String[1];
                ids[0] = scenicId;
                this.mapper.deleteScenicAdminByIds(ids);

                //增加后台用户
                backUserId = SnowIdUtil.getInstance().nextId();
                backUser.setId(backUserId).setCipher(MD5Util.Base64Encode(password))
                        .setPassword(MD5Util.createPassword(MD5Util.getMD5String(password), backUserId))
                        .setCreateTime(new Date())
                        .setRoleId(VariableConstants.STRING_CONSTANT_1)
                        .setIsUsing(Short.valueOf("1"))
                        .setIsDelete(Short.valueOf("0"))
                        //账号类型
                        .setAccountType(unitType);
                //单位类型为机构则必传机构类型
                if (VariableConstants.STRING_CONSTANT_2.equals(unitType)) {
                    if (organType == null || organType.equals("")) {
                        throw new BusinessException("organType.is.null", "请传入机构类型");
                    }
                    backUser.setOrganType(organType);
                }

                this.backUserService.insert(backUser);


                /** s_users也要有一个相同的账号，景区id一致 */

              /* users.setId(backUserId)
                        .setPassword(MD5Util.createPassword(MD5Util.getMD5String(password),backUserId))
                        .setDelFlag(Short.valueOf("0"))
                        .setUserType(VariableConstants.STRING_CONSTANT_2)
                        .setCreateTime(new Date())
                        .setAssumeOffice(Short.valueOf("1"));
                this.usersService.insert(users);*/

                /** 通过审核,就必须新建该单位的考勤审批设置 */
                this.visualRangeSettingService.insertVisualRangeSettingByScenicInfoId(scenicId);
            }
            //审核状态更改为审核
            result = this.mapper.updateAuditStatusToOneById(scenicId, backUserId);
        } else {
            /** 拒绝通过 */
            //查询景区是否是已经通过审核的，若通过审核就要删除scenicAdmin,并把状态改为通过
            boolean isPass = this.testScenicIsPass(scenicId);
            if (isPass) {
                //删除景区管理员表
                String[] ids = new String[1];
                ids[0] = scenicId;
                this.mapper.deleteScenicAdminByIds(ids);
                //原来是通过审核的，再次重新申请一次，拒绝，所以回到了原来已经通过的状态，后台用户账号不变动
                result = this.mapper.updateAuditStatusToOneById(scenicId, null);
            } else {
                result = this.mapper.updateAuditStatusToTwoById(scenicId);
            }

        }
        return result;
    }

    /**
     * @方法名：selectBackUserIdByScenicId
     * @描述： 通过景区id查询后台用户的id
     * @作者： kjz
     * @日期： Created in 2020/2/24 13:41
     */
    private String selectBackUserIdByScenicId(String scenicId) {
        return this.mapper.selectBackUserIdByScenicId(scenicId);
    }

    /**
     * @方法名：testScenicIsPass
     * @描述： 检测景区是否已经通过审核
     * @作者： kjz
     * @日期： Created in 2020/2/24 13:30
     */
    private boolean testScenicIsPass(String scenicId) {
//        String auditStatus = this.mapper.selectAuditStatusByScenicId(scenicId);
//        return auditStatus.equals("1")?true:false;
        String isPassed = this.mapper.selectIsPassedByScenicId(scenicId);
        if (isPassed != null && VariableConstants.STRING_CONSTANT_1.equals(isPassed)) {
            return true;
        }
        return false;
    }

    /**
     * @方法名：deleteScenicInfoByIds
     * @描述： 批量删除景区信息
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/22 11:57
     */
    @Transactional(rollbackFor = BusinessException.class)
    public int deleteScenicInfoByIds(String ids) {
        int result = 0;
        String[] split = ids.split(",");
        if (split.length > 0) {
            //删除景区表
            result = this.mapper.deleteScenicInfoByIds(split);
            //删除景区管理员表
            this.mapper.deleteScenicAdminByIds(split);
            //删除后台用户表
            this.mapper.deleteBackUserByScenicId(split);
            //删除s_users用户表
            this.mapper.deleteUsersByScenicId(split);
            //删除审批范围设置
            this.mapper.deleteVisualRangeSettingByScenicInfoId(split);
        }
        return result;

    }

    /**
     * @方法名：importScenicInfoExcel
     * @描述： excel导入景区数据
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/2/22 16:55
     */
    @Transactional(rollbackFor = BusinessException.class)
    public Boolean importScenicInfoExcel(String fileName, MultipartFile file, String unitType) {
        boolean notNull = false;
        List<InsertOrUpdateScenicVo> insertOrUpdateScenicVos = new ArrayList<InsertOrUpdateScenicVo>();

        Workbook wb = ExcelUtil.createWorkBook(fileName, file);

        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }
        System.err.println(sheet.getLastRowNum());
        for (int r = 2; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            InsertOrUpdateScenicVo insertOrUpdateScenicVo = new InsertOrUpdateScenicVo();
            System.out.println(row.getCell(0).getCellType());
            ;
            /** 区域编码 */
            if (row.getCell(0).getCellType() != 1) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,区域编码请设为文本格式)");
            }

            //区域编码
            String districtId = row.getCell(0).getStringCellValue();

            if (districtId == null || districtId.isEmpty()) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,区域编码未填写)");
            }

            /** 景区名字 */
            if (row.getCell(1).getCellType() != 1) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,景区名字请设为文本格式)");
            }
            //景区名字
            String scenicName = row.getCell(1).getStringCellValue();
            if (scenicName == null || scenicName.isEmpty()) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,景区名字未填写)");
            }

            /** 公司名字 */
            if (row.getCell(2).getCellType() != 1) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,公司名字请设为文本格式)");
            }
            //公司名字
            String corpName = row.getCell(2).getStringCellValue();
            if (corpName == null || corpName.isEmpty()) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,公司名字未填写)");
            }

            /** 景区管理员 */
            /*if( row.getCell(3).getCellType() !=1){
                throw new BusinessException("import.failure","导入失败(第"+(r+1)+"行,景区管理员姓名请设为文本格式)");
            }
            //景区管理员
            String adminName = row.getCell(3).getStringCellValue();
            if(adminName==null || adminName.isEmpty()){
                throw new BusinessException("import.failure","导入失败(第"+(r+1)+"行,景区管理员姓名未填写)");
            }*/

            /** 联系电话 */
            if (row.getCell(3).getCellType() != 1) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,联系电话请设为文本格式)");
            }
            //联系电话
            String phone = row.getCell(3).getStringCellValue();
            /*if(phone==null || phone.isEmpty()){
                throw new BusinessException("import.failure","导入失败(第"+(r+1)+"行,联系电话未填写)");
            }*/

            /** 身份证号 */
            /*if( row.getCell(5).getCellType() !=1){
                throw new BusinessException("import.failure","导入失败(第"+(r+1)+"行,身份证号请设为文本格式)");
            }
            //身份证号
            String identityCard = row.getCell(5).getStringCellValue();
            if(identityCard==null || identityCard.isEmpty()){
                throw new BusinessException("import.failure","导入失败(第"+(r+1)+"行,身份证号未填写)");
            }*/

            /** 性别 */
           /* if( row.getCell(6).getCellType() !=1){
                throw new BusinessException("import.failure","导入失败(第"+(r+1)+"行,性别请设为文本格式)");
            }
            //性别
            String gender = row.getCell(6).getStringCellValue();
            if(gender==null || gender.isEmpty()){
                throw new BusinessException("import.failure","导入失败(第"+(r+1)+"行,性别未填写)");
            }
            gender = gender.equals("男")?"1":gender.equals("女")?"2":"3";*/

            /** 管理员账号 */
            if (row.getCell(4).getCellType() != 1) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,管理员账号请设为文本格式)");
            }
            //管理员账号
            String account = row.getCell(4).getStringCellValue();
            if (account == null || account.isEmpty()) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,管理员账号未填写)");
            }

            /** 管理员密码 */
            if (row.getCell(5).getCellType() != 1) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,管理员密码请设为文本格式)");
            }
            //管理员密码
            String password = row.getCell(5).getStringCellValue();
            if (password == null || password.isEmpty()) {
                throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,管理员密码未填写)");
            }

            //单位类型==景区时，要传入 当日最大承载量
            if (unitType.equals(VariableConstants.STRING_CONSTANT_1)) {
                /** 当日最大承载量 */
                if (row.getCell(6).getCellType() != 1) {
                    throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,当日最大承载量请设为文本格式)");
                }
                //当日最大承载量
                String maximumCapacityForTheDayDisplay = row.getCell(6).getStringCellValue();
                if (maximumCapacityForTheDayDisplay == null || maximumCapacityForTheDayDisplay.isEmpty()) {
                    throw new BusinessException("import.failure", "导入失败(第" + (r + 1) + "行,当日最大承载量未填写)");
                }

                BigInteger maximumCapacityForTheDay = new BigInteger(maximumCapacityForTheDayDisplay);
                insertOrUpdateScenicVo.setMaximumCapacityForTheDay(maximumCapacityForTheDay);
            }

            insertOrUpdateScenicVo.setDistrictId(districtId)
                    .setScenicName(scenicName).setCorpName(corpName).setPhone(phone)
//                    .setAdminName(adminName)
//                    .setIdentityCard(identityCard).setGender(gender)
                    .setAccount(account).setPassword(password)
                    //单位类型
                    .setUnitType(unitType);

            insertOrUpdateScenicVos.add(insertOrUpdateScenicVo);
        }
        insertOrUpdateScenicVos.forEach(insertScenicVo -> {
            try {
                insertOrUpdateScenicInfo(insertScenicVo);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        return notNull;

    }

    /**
     * @方法名：reapplyScenicInfo
     * @描述： 已通过和已拒绝的重新申请景区账号
     * @作者： kjz
     * @日期： Created in 2020/2/25 0:08
     */
    @Transactional(rollbackFor = BusinessException.class)
    public int reapplyScenicInfo(InsertOrUpdateScenicVo insertOrUpdateScenicVo) throws ParseException {
        //最终返回结果
        int result = 0;
        //景区id
        String scenicId = insertOrUpdateScenicVo.getScenicId();
        //身份证号
        String identityCard = insertOrUpdateScenicVo.getIdentityCard();
        //电话号码
        String phone = insertOrUpdateScenicVo.getPhone();
        //性别
        String gender = insertOrUpdateScenicVo.getGender();
        //账号
        String account = insertOrUpdateScenicVo.getAccount();
        //管理员密码
        String password = insertOrUpdateScenicVo.getPassword();
        //当日最大承载量
        BigInteger maximumCapacityForTheDay = insertOrUpdateScenicVo.getMaximumCapacityForTheDay();
        //单位类型
        String unitType = insertOrUpdateScenicVo.getUnitType();
        //机构类型
        String organType = insertOrUpdateScenicVo.getOrganType();
        //设备编号
        String equipmentNumbers = insertOrUpdateScenicVo.getEquipmentNumber();
        //文旅资源状态【1.应急】
        Integer emergency = insertOrUpdateScenicVo.getEmergency();
        //文旅资源状态【1.应急】
        String emergencyId = insertOrUpdateScenicVo.getEmergencyId();
        //文旅资源状态【1.应急】
        String resourceType = insertOrUpdateScenicVo.getResourceType();


        //新增景区时 当日最大承载量不能为空
        if (VariableConstants.STRING_CONSTANT_1.equals(unitType)) {
            //新增景区时 当日最大承载量不能为空
            if (maximumCapacityForTheDay == null) {
                throw new BusinessException("maximumCapacityForTheDay.is.null");
            }
        } else if (VariableConstants.STRING_CONSTANT_2.equals(unitType)) {
            //新增机构时,机构类型不能为空
            if (organType == null || organType.equals("")) {
                throw new BusinessException("organType.is.null");
            }
        }
        //验证名称是否重复
        judgeUnauditedScenicNameIsReDo(insertOrUpdateScenicVo.getScenicName(),scenicId,resourceType);
        //验证身份证号的数据有效性
        /*if(!ValidateUtil.validateIDCard(identityCard)){
            throw new BusinessException("wrong.id.number");
        }*/

        //验证电话号码的数据有效性
        if (phone != null && !phone.equals("")) {
            if (PhoneUtil.isPhone(phone) == null) {
                throw new BusinessException("phone.is.mistake");
            }
        }


        //验证性别的数据有效性
       /* if(!VariableConstants.STRING_CONSTANT_1.equals(gender) && !VariableConstants.STRING_CONSTANT_2.equals(gender)){
            throw new BusinessException("gender.is.fault");
        }*/

        String backUserId = insertOrUpdateScenicVo.getBackUserId();
        if (backUserId == null || backUserId.equals("")) {
            /** 之前是已拒绝,从未申请成功*/
            this.insertOrUpdateScenicInfo(insertOrUpdateScenicVo);

        } else {
            /** 之前是已通过*/
            ScenicInfo scenicInfo = new ScenicInfo()
                    .setId(scenicId).setScenicName(insertOrUpdateScenicVo.getScenicName())
                    .setCorpName(insertOrUpdateScenicVo.getCorpName())
                    .setDistrictId(insertOrUpdateScenicVo.getDistrictId())
                    .setUpdateTime(LocalDateTime.now())
                    //添加之前已经通过的标识
                    .setIsPassed(VariableConstants.STRING_CONSTANT_1);

            //应急文旅资源状态
            if (emergency != null && emergency == 1) {
                scenicInfo.setEmergency(emergency);
                scenicInfo.setEmergencyId(emergencyId);
                //如果资源为应急文旅资源，那么应急资源ID必须存在
                if (StringUtils.isBlank(emergencyId)){
                    throw new BusinessException("Emergency.Resource.Format.Error","应急文旅资源数据异常！");
                }
                //判断应急文旅资源是否已经存在
                judgeEmergencyIdIsReDo(emergencyId, scenicId);
            }


            //设备编号
            if (!StringUtil.isBlank(equipmentNumbers)) {
                List<String> numbers = Arrays.asList(equipmentNumbers.split(","));
                judgeEquipmentNumberRepetition(numbers, scenicId);
                HashSet<String> equipmentNumberSet = new HashSet<>(numbers);
                StringBuilder equipmentNumberSB = new StringBuilder();
                int i = 0;
                for (String number : equipmentNumberSet) {
                    equipmentNumberSB.append(number);
                    if (i < equipmentNumberSet.size() - 1) {
                        equipmentNumberSB.append(",");
                        i++;
                    }
                }
                String equipmentNumberStr = equipmentNumberSB.toString();
                scenicInfo.setEquipmentNumber(equipmentNumberStr);
            }


            if (unitType.equals(VariableConstants.STRING_CONSTANT_1)) {
                scenicInfo.setMaximumCapacityForTheDay(maximumCapacityForTheDay);
            }
            System.err.println("重新申请：" + scenicInfo);
            this.mapper.updateScenicInfoSelective(scenicInfo);

            //删除景区管理员表
            String[] ids = new String[1];
            ids[0] = scenicId;
            this.mapper.deleteScenicAdminByIds(ids);

            ScenicAdmin scenicAdmin = new ScenicAdmin()
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setScenicId(scenicId)
                    .setCreateTime(LocalDateTime.now())
                    //身份证号
//                    .setIdentityCard(identityCard)
                    //电话号码
                    .setPhone(phone)
                    //性别
//                    .setGender(gender)
                    //景区管理员姓名
                    .setName(insertOrUpdateScenicVo.getAdminName())
                    //账号
                    .setAccount(account)
                    //密码
                    .setPassword(MD5Util.Base64Encode(password));

            this.scenicAdminService.insert(scenicAdmin);
        }

        result = this.mapper.updateAuditStatusToZeroById(scenicId);
        return result;
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(PhoneUtil.isPhone("10320835344"));
    }


    public Integer selectBackUserByEmergencyId(String emergencyId, String id) {
        return scenicInfoMapper.selectScenicInfoByEmergencyId(emergencyId, id);
    }
    public Integer countScenicInfoByEmergencyId(String scenicName, String id) {
        return scenicInfoMapper.countScenicInfoByScenicName(scenicName, id);
    }
}
